package com.spsecurity.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * @create 2022-03-2022/3/15-17:06
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    //链式编程
    //httpSecurity授权
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //super.configure(http);
        //请求规则
        //首页所有人可以访问antMatchers()添加请求路径, permitAll()
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/index").permitAll()
                .antMatchers("/index.html").permitAll()
                //功能页 hasRole(),hasAnyRole()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");

        //没有权限自动到登陆界面
        //定制登录页
        http.formLogin().loginPage("/toLogin").usernameParameter("username").passwordParameter("password").loginProcessingUrl("/login");

        //注销功能
        http.logout().logoutSuccessUrl("/");
        //关闭网站csrf功能
        http.csrf().disable();
        //开启rememberMe功能，自定义rememnerME
        http.rememberMe().rememberMeParameter("remember");
        ;
    }

    //认证
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //数据库获取
        //密码编码:PasswordEncode   .passwordEncoder(new BCryptPasswordEncoder())
        //and拼接
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("wwww").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2")
                .and()
                .withUser("2").password(new BCryptPasswordEncoder().encode("2")).roles("vip3")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
                .and()
                .withUser("4").password("4").roles("vip1","vip2","vip3");

    }



}
